package com.cskaoyan.wxcontroller;


import com.cskaoyan.bean.baseresultVO.*;
import com.cskaoyan.bean.domain.Admin;
import com.cskaoyan.bean.domain.User;
import com.cskaoyan.shiro.MallToken;
import com.cskaoyan.utils.Md5Util;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Map;

/**
 * 整合shiro框架
 */
@RestController
@RequestMapping("wx/auth")
public class WxAuthController {

    /**
     * 1.管理员密码采用md5加密，登录前先生成md5再去数据库进行比对
     */
    @PostMapping("login")
    public BaseRespVo<LoginUserData> login(@RequestBody Map map) {
        String username = (String)map.get("username");
        String password = (String)map.get("password");
        String passwordWithMd5 = null;
        try {
            passwordWithMd5 = Md5Util.getMd5AdDefaultSalt(password);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        Subject subject = SecurityUtils.getSubject();
        //UsernamePasswordToken authenticationToken = new UsernamePasswordToken(username, passwordWithMd5);
        MallToken authenticationToken = new MallToken(username, passwordWithMd5, "wx");
        subject.login(authenticationToken);
        /**
         * 获得认证状态
         * boolean authenticated = subject.isAuthenticated();
         *获得用户信息
         *Object primaryPrincipal = subject.getPrincipals().getPrimaryPrincipal();
         */
        WeChatLoginData loginData = new WeChatLoginData();
        UserInfoBean userInfoBean = new UserInfoBean();
        /**
         * 从session中获取对象
         */
        User user = (User) subject.getPrincipals().getPrimaryPrincipal();
        userInfoBean.setAvatar(user.getAvatar());
        userInfoBean.setNickName(user.getNickname());
        loginData.setUserInfo(userInfoBean);
        loginData.setToken((String) subject.getSession().getId());
        //备用
        //request.getServletContext().setAttribute("username",username);
        //request.getSession().setAttribute("username",username);
        return BaseRespVo.ok(loginData);

    }



    /**
     * @return
     */
    @RequestMapping("logout")
    public BaseRespVo logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return BaseRespVo.ok(null);
    }
}
